#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
using namespace std;

__thread int g_val = 0;

void *threadRoutine(void *args)
{
    pthread_detach(pthread_self());
    while (1)
    {
        cout << (char *)args << ":" << g_val << " &:" << &g_val << endl;
        g_val++;
        sleep(1);
        break;
    }
    pthread_exit((void *)12);

    //--------------------------------------------------------------
    // int i = 0;
    // while (1)
    // {
    //     cout << "新线程：" << (char *)args << "运行中..." << endl;
    //     sleep(1);

    //     // if (i++ == 3)
    //     // {
    //     //     break;
    //     // }
    // }
    // //exit(1);//终止整个进程的！！
    // pthread_exit((void*)12);
    // return (void*)10;
}
int tickets = 5000;

void *getTickets(void *args)
{
    (void)args;
    while (1)
    {
        usleep(1000);
        printf("tid: %p--ticket: %d\n", pthread_self(), tickets);
        tickets--;
        if (tickets <= 0)
            break;
    }
    // pthread_exit((void*)0);
    return nullptr;
}

int main()
{
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, nullptr, getTickets, nullptr);
    pthread_create(&tid2, nullptr, getTickets, nullptr);
    pthread_create(&tid2, nullptr, getTickets, nullptr);

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);

    //------------------------------------------------------------------
    // pthread_t tid;
    // pthread_create(&tid, nullptr, threadRoutine, (void *)"thread 1");

    // sleep(2);
    // while(1)
    // {
    //     cout<<"主线程"<<":"<<g_val<<" &:"<<&g_val<<endl;
    //     sleep(2);
    //     break;
    // }
    // void* ret = nullptr;
    // int n = pthread_join(tid,&ret);

    // if(n==0)
    // {
    //     cout<<"等待分离线程退出成功"<<(long long)ret<<endl;
    // }
    // else
    // {
    //     cout<<"等待分离线程退出失败"<<(long long)ret<<endl;
    // }
    //-------------------------------------------------------
    // pthread_t tid;

    // pthread_create(&tid, nullptr, threadRoutine, (void *)"thread 1");
    // sleep(3);
    // pthread_cancel(tid);

    // void* ret = nullptr;
    // pthread_join(tid,&ret);

    // cout << "主线程执行中...." << endl;
    // //sleep(3);
    // cout << "主线程执行结束...." << (long long)ret << endl;
    return 0;
}